# -*- coding=utf-8 -*-

"""
redis model base
"""
from framework.model import Model
import redis
from config.cfg import db_cfg

class RedisModel(Model):
    """
    redis db model base
    """
    db = None  # redis db object
    current_db = None  # mongo db name
    current_client = None  # mogo db connection
    default = False
    collection = None

    def __init__(self, **kwargs):
        """
        init
        """
        super(RedisModel, self).__init__(**kwargs)
        if not self.load_db():
            raise redis.ConnectionError("load redis error")

    def load_db(self, name="default"):
        """
        from config load mongo db
        :param name: confing mongodb connection name
        :return: bool
        """
        if isinstance(db_cfg, tuple):
            for item in db_cfg:
                if isinstance(item, dict):
                    if "name" in item.keys() and "type" in item.keys():
                        if item.get("type") == 'redis':
                            if name == 'default' and item.get("default"):
                                if self.default:
                                    return True

                                self.current_db = item.get("name")
                                self.default = True

                            if item.get("name") == name:
                                if self.current_db == name:
                                    return True

                                self.current_db = name
                                self.default = False

                            pool = redis.ConnectionPool(host=item.get("host"), port=item.get("port"), db=item.get("db"))
                            self.db = redis.Redis(connection_pool=pool)
                            self.current_client = item.get("db")
                            self.__table__ = self.get_collection()
                            return True

        return False


    def get_collection(self):
        """
        
        :return: 
        """
        return 'collection_name'

    def find_one(self, where):
        """
        
        :param where: 
        :return: 
        """
        pass

    def save(self):
        """
        save to 
        :return: 
        """
        pass

    def update(self):
        """
        update
        :return: 
        """
        pass

    def insert(self):
        """
        insert mongodb
        :return: 
        """
        pass